<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共 {{ page.total }} 条记录</span>
        <template v-slot:after>
          <el-button size="small" type="warning" @click="$router.push('/import?type=user')">导入</el-button>
          <el-button size="small" type="danger" @click="exportData">导出</el-button>
          <el-button size="small" type="primary" @click="dialogVisible = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table v-loading="loading" border :data="list">
          <!-- sortable 表示可排序 -->
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column
            label="头像"
          >
            <template slot-scope="{row}">
              <img v-imagedirec="require('@/assets/common/img.jpeg')" :src="row.staffPhoto" alt="" style="border-radius: 50%; width: 100px; height: 100px; padding: 10px" @click="showQrcode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="format" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <!-- 作用域插槽 格式化 prop="timeOfEntry"-->
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template v-slot="{ row }">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showAlloRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <!-- @current-change="changePage"  current-change 控制 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :page-size="page.size" :current-page="page.page" :total="page.total" @current-change="changePage" />
        </el-row>
      </el-card>
    </div>
    <!-- 新增员工弹出层 -->
    <add-employee :dialog-visible.sync="dialogVisible" />
    <!-- 头像二维码弹出层 -->
    <!-- TODO: @close="imgUrl=''" 干啥使得 -->
    <el-dialog
      title="二维码"
      :visible.sync="qrcodedialogVisible"
    >
      <el-row type="flex" justify="center">
        <canvas ref="qrcode" />
      </el-row>
    </el-dialog>
    <!-- 角色分配弹窗 -->
    <allo-role ref="alloRoleRef" :allo-role-dialog-visible.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
// addEmployee
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeNum from '@/components/constant/employees'
import AddEmployee from './components/add-employee.vue'
import AlloRole from './components/assign-role.vue'
import { formatDate } from '@/filters'
import QRcode from 'qrcode'
export default {
  name: 'EmployeeIndex',
  components: {
    AddEmployee,
    AlloRole
  },
  props: {},
  data () {
    return {
      dialogVisible: false, // 新增员工弹窗控制
      loading: false, // 加载遮盖层
      list: [], // 接收员工数据
      // 分页数据
      page: {
        page: 1,
        size: 10, // 每页数据条数
        total: 0 // 总页数
      },
      qrcodedialogVisible: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created () {
    this.getEmployeeList()
  },
  methods: {
    // 页码改变
    changePage (newPage) {
      // console.log(newPage)
      this.page.page = newPage
      this.getEmployeeList()
    },
    // 获取员工数据
    async getEmployeeList () {
      this.loading = true
      // 此处传入的整个参数是 this.page 数组
      const { total, rows } = await getEmployeeList(this.page)
      // console.log(result)
      this.page.total = total
      this.list = rows // 此处不用响应式添加??
      // console.log(this.list) // 此处的时间不需要格式化  就当了解一下操作吧
      this.loading = false
    },
    // 格式化时间
    format (row, column, cellValue, index) {
      // find 返回查找到的第一个元素
      const obj = EmployeeNum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
      // 新增的员工没有数据
    },
    // 删除员工
    async delEmployee (id) {
      try {
        await this.$confirm('您确定删除该员工吗？')
        await delEmployee(id)
        this.getEmployeeList()
        this.$message('操作成功！')
      } catch (error) {
        console.log(error)
      }
    },
    // 導出數據
    exportData () {
      import('@/vendor/Export2Excel').then(async excel => {
        // excel 是 Export2Excel 文件的導出對象
        const headers = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        // console.log(res)
        const data = this.formatData(headers, rows)
        const multiHeader = [['姓名', '主要信息', '', '', '', '部門']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头-行菜單
          data, // 具体数据 必填
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx',
          multiHeader, // 複雜表頭
          merges // 合并表頭
        })
      })
    },
    // 格式化數據
    formatData (headers, rows) {
      // 簡寫
      // TODO: 這個地方不是很懂 ?? 追上去再解決
      // return rows.map(item => Object.keys(headers).map(key => { item[headers[key]] }))
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            console.log(EmployeeNum.hireType)
            const obj = EmployeeNum.hireType.find(subitem => subitem.id === item[headers[key]])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    // 生成二维码
    showQrcode (url) {
      if (url) {
        // 先渲染界面
        this.qrcodedialogVisible = true
        // 变异步为同步
        this.$nextTick(() => {
          QRcode.toCanvas(this.$refs.qrcode, url)
        })
      } else {
        this.$message.warning('该用户还没有设置头像')
      }
    },
    // 展示分配角色页面
    async showAlloRole (id) {
      this.userId = id
      // 不明白这里为什么要双重async await
      await this.$refs.alloRoleRef.getUserDetailById(id)
      this.showRoleDialog = true
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
